home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 15772 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: hubcap.clemson.edu!hubcap!mjs
  2. From: mjs@hubcap.clemson.edu (M. J. Saltzman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Array indexing with malloc
  5. Date: 19 Apr 96 15:24:33 GMT
  6. Organization: Clemson University
  7. Message-ID: <mjs.829927473@hubcap>
  8. References: <96110.093936F0O@psuvm.psu.edu>
  9. NNTP-Posting-Host: hubcap.clemson.edu
  10. X-Newsreader: NN version 6.5.0 #1
  11.  
  12. Tim Benner <F0O@psuvm.psu.edu> writes:
  13.  
  14. >Hi netters!
  15.  
  16. >   I write c programs to collect online data, and I always malloc a block
  17. >of memory to hold the data.  I set the memory block up such that each
  18. >row is a different time point, and each column is a different channel.
  19. >   The formula I use to do this is:
  20. >         RawData[CurrentPoint*NumChannels+Channel]
  21. >   This works fine, except I don't like having to do the multiplication
  22. >every time I want to access a point in the memory block.  I tried setting
  23.  
  24. If the number of channels is known at compile time, you could do this:
  25.  
  26.     data_t  (*RawData)[NUM_CHANNELS];
  27.  
  28.     RawData = malloc(NUM_POINTS * NUM_CHANNELS * sizeof(data_t));
  29.  
  30.     RawData[CurrentPoint][Channel] ...
  31.  
  32. Otherwise, you could use a dynamic multidimensional array (as described
  33. in the FAQ), and access it the same way.
  34.  
  35. >up the memory block by mallocing a structure.  This also works, and I
  36. >believe is neater in implementation, but seems to have a limit of about
  37. >64k.  I allocate arrays of around 100k or more.
  38. >   My burning question is, can I use a structure rather then the above
  39. >method for accessing large arrays?  I'm using Turbo C++ version 3.0, and
  40.  
  41. Do you mean soemthing like
  42.  
  43.     struct point_t {
  44.       data_t channel1, channel2, ..., channeln;
  45.     } *RawData;
  46.  
  47.     RawData = malloc(NUM_POINTS * sizeof(struct point_t));
  48.  
  49.     RawData[i].channel1 ...
  50.     etc.
  51.  
  52. You could do this, but you lose the ability to loop over channels.
  53. If that's not what you had in mind, post some code.
  54.  
  55. Note that all the address calculations involve that multiplication (or
  56. something similar), at least behind the scenes.
  57. -- 
  58.         Matthew Saltzman
  59.         Clemson University Math Sciences
  60.         mjs@clemson.edu
  61.